package com.example.springboot_manage.controller;

import com.example.springboot_manage.service.UploadService;
import com.example.springboot_manage.util.FileResult;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Controller;
import org.springframework.web.bind.annotation.*;
import org.springframework.web.multipart.MultipartFile;
import org.springframework.web.servlet.mvc.support.RedirectAttributes;

import java.io.IOException;
import java.nio.file.Files;
import java.nio.file.Path;
import java.nio.file.Paths;
import java.time.LocalDateTime;
import java.time.format.DateTimeFormatter;

@Controller("/file")
public class UploadController {

    private static String UPLOADED_FOLDER = "D:\\学习文件\\A-new\\SpringBoot_manage\\src\\main\\resources\\static\\images\\";

    @GetMapping("/uploadResult")
    public String uploadStatus()
    {
        return "uploadResult";
    }

    @PostMapping("/upload")
    public String singleFileUpload(@RequestParam("file") MultipartFile file, RedirectAttributes redirectAttributes)
    {
        if (file.isEmpty())
        {
            redirectAttributes.addFlashAttribute("message", "Please select a file to upload");
            return "redirect:uploadResult";
        }
        try
        {
            byte[] bytes = file.getBytes();
            Path path = Paths.get(UPLOADED_FOLDER + file.getOriginalFilename());
            Files.write(path, bytes);

            redirectAttributes.addFlashAttribute("message", "Successfully uploaded '" + file.getOriginalFilename() + "'");
        }
        catch (IOException e)
        {
            e.printStackTrace();
        }
        return "redirect:/uploadResult";
    }


    @Autowired
    private UploadService uploadService;

    /**
     * 上传七牛云
     * @param file
     * @return
     * @throws IOException
     */
    @RequestMapping("save")
    @ResponseBody
    public FileResult upload(MultipartFile file) throws IOException {
        String filename = file.getOriginalFilename();
        String date = DateTimeFormatter.ofPattern("yyyy/MM/dd/").format(LocalDateTime.now());
        filename = date+System.currentTimeMillis()+filename.substring(filename.lastIndexOf("."));
        return uploadService.upload(file.getInputStream(),filename);
    }



}
